// pages/order/order.js

//获取app实例
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeIndex: 0, //当前选中的类型
    sliderOffset: 0, //滑块偏移距离
    sliderLeft: 0, //滑块初始left值
    sliderWidth: 67, //滑块初始width值
    orderList: [], //订单列表
    isNone: false, //false隐藏为空提示， true显示为空提示
    emptyTip: {
      font: "您暂时还没有订单哦~",
      imgUrl: "https://rybc.0791jr.com/WeChat/images/empty-korder.png"
    },
    cancelOrderReason: [
      '订单信息填写错误',
      '错拍/多拍/不想要',
      '未按要定时间发货',
      '其他原因'
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (!app.globalData.userId) {
      app.userLogin(() => this.init(options.jk));
    } else {
      this.init(options.jk);
    }
    console.log(options);
    const activeIndex = options.type, //选中的下标
    query = wx.createSelectorQuery();  //创建节点选择器
    query.select('.navbar__item').boundingClientRect();
    query.exec((res) => {
      //res就是 该元素的信息 数组
      const width = res[0].width || this.data.sliderWidth;
      this.setData({
        activeIndex: activeIndex,
        sliderOffset: width * activeIndex,
        jk: options.jk
      })
    });
  },

  //初始化我的订单
  init(jk,cb) {
    this.setData({ 
      orderList: null,
      isNone: false 
    });
    wx.showLoading({ title: '加载中'});
    wx.request({
      url: app.baseURL + 'Order&a=' + jk,
      data: { user_id: app.globalData.userId },
      success: (res) => {
        if (res.statusCode == 200) {
          this.setData({ 
            orderList: res.data.result,
            isNone: !res.data.result.length  
          });
          typeof cb == 'function' && cb();
          wx.hideLoading();
        }
      }
    })
  },

  //切换类型
  tabClick: function (e) {
    console.log(e)
    const jk = e.currentTarget.dataset.jk,
      id = e.currentTarget.id,
      left = e.currentTarget.offsetLeft,
      oldLeft = this.options.type;
    this.setData({
      //translateX的值就是终点目标距离左边的距离减去初始left的值
      sliderOffset: left,
      activeIndex: id,
    });
    this.init(jk);
  },

  // 取消订单
  CancellationOfOrder(e){
    let submitData = {
      user_id: app.globalData.userId,
      order_id: e.currentTarget.dataset.id,
      status: e.currentTarget.dataset.status,
      type: 1
    }
    //加载中提示
    wx.showLoading({ title: '加载中' });    
    //发送取消订单请求
    wx.request({
      url: app.baseURL + 'Order&a=del_order',
      data: submitData,
      success: (res) => {
        if (res.statusCode == 200) {
          if (res.data.status == 2) {
            //前往结果页面
            wx.reLaunch({ url: "/pages/commentResult/commentResult?title=操作成功&tip=您已成功取消订单" });
            wx.hideLoading();          
          } else {
            wx.showToast({
              title: '取消失败，请重试', icon: 'none'
            }) 
          }
        }  
      },
      fail: (res) => {
        wx.hideLoading();
        wx.showToast({ title: '网络错误', icon: 'none' })
      }
    })
  },
  // 删除订单
  clicktoDelete(e) {
    let orders = this.data.orders;
    const orderId = e.currentTarget.dataset.id;
    const index = e.currentTarget.dataset.index;
    const orderStatus = e.currentTarget.dataset.status;
    wx.showModal({
      title: '温馨提示',
      content: '确定删除当前商品吗？',
      confirmColor: "#f00",
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '加载中' });
          wx.request({
            url: app.baseURL + 'Order&a=del_order',
            data: {
              user_id: app.globalData.userId,
              order_id: orderId,
              status: orderStatus,
              type: 2
            },
            success: (res) => {
              if (res.statusCode == 200) {
                if (res.data.status == 4) {
                  //前往结果页面
                  wx.reLaunch({ url: "/pages/commentResult/commentResult?title=删除成功&tip=您已成功删除此订单" });
                } else {
                  wx.hideLoading();
                  wx.showToast({ title: '删除失败，请重试', icon: 'none' })
                }
              }  
            },
            fail: (res) => {
              wx.hideLoading();
              wx.showToast({ title: '网络错误', icon: 'none' })
            }
          });
        }
      }
    })
  },

  // 确认收货
  confirmReceipt(e){
    let order_id=e.currentTarget.dataset.order_id;
    wx.showModal({
      title: '温馨提示',
      content: '是否确认收货？',
      confirmColor: "#f00",
      success: (res)=>{
        if (res.confirm){
          //加载中提示
          wx.showLoading({  title: '加载中' });
          //发送收货请求
          wx.request({
            url: app.baseURL + 'Order&a=getted',
            data: {
              user_id: app.globalData.userId,
              order_id: order_id
            },
            success: (res) => {
              if (res.statusCode == 200) {
                if (res.data.status == 1){
                  wx.hideLoading();
                  //前往结果页面
                  wx.reLaunch({
                    url: "/pages/commentResult/commentResult?title=操作成功&tip=您已成功收货"
                  }) 
                } else if (res.data.status == 2) {
                  //收货失败
                  wx.hideLoading();
                  wx.showToast({ title: '操作失败，请重试', icon: 'none' })
                }
              }  
            },
            fail: (res) => {
              wx.hideLoading();
              wx.showToast({ title: '网络错误', icon: 'none' })
            }
          })
        }
      }
    })
  },

  //去评价跳转
  toComment(e) {
    console.log(e.currentTarget.dataset.item)
    let info = JSON.stringify(e.currentTarget.dataset.item);
    wx.navigateTo({
      url: '/pages/comment/comment?info=' + info
    });
  },
  // 查看详情
  toDetail(e){
    let info = JSON.stringify(e.currentTarget.dataset.item);
    wx.navigateTo({
      url: '/pages/orderDetail/orderDetail?info=' + info + '&orderId=' + e.currentTarget.dataset.item.id
    });
  },

  //查看商品信息
  toGoods(e){
    const pid = e.currentTarget.dataset.pid,
      item_id = e.currentTarget.dataset.item_id,
      a_id = e.currentTarget.dataset.a_id;
      //判断是否拼团订单
    if (!pid || pid == 0){   //不是拼团订单  -->  普通订单商品详情
      wx.navigateTo({
        url: "/pages/detail/detail?item_id=" + item_id,
      })
    } else if (pid != 0) {   //是拼团订单  -->  拼团订单商品详情
      wx.navigateTo({
        url: "/pages/groupDetail/groupDetail?item_id=" + item_id + '&a_id=' + a_id,
      })
    }
  },

  // 立即支付
  clicktoPay(e) {   
    let info = e.currentTarget.dataset.info;
    delete info.item_info;
    let info_json = JSON.stringify(info);
    wx.navigateTo({
      url: '/pages/orderPay/orderPay?result=' + info_json
    })
  },

  //更新数据函数
  updateOrder(data) {
    this.setData({
      orders: data
    })
  },

  // 转发
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      const pid = res.target.dataset.pid;
      let img = "https://rybc.0791jr.com/data/attachment/item/" + res.target.dataset.img;
      return {
        title: '拼团',
        path: '/pages/groupStatus/groupStatus?pid=' + pid,
        imageUrl: img
      }
    }
  }
})